package com.lagou.edu.filter;

import com.lagou.edu.config.RegisterLimitConfig;
import com.lagou.edu.util.RegisterChecker;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
@RefreshScope
public class RegisterLimitFilter implements GlobalFilter, Ordered {
    @Value("${register.limitMinutes}")
    private int limitMinutes;

    @Value("${register.limitCount}")
    private int limitCount;

    private RegisterChecker registerChecker = new RegisterChecker();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        RegisterLimitConfig registerLimitConfig = new RegisterLimitConfig();
        registerLimitConfig.setLimitMinutes(limitMinutes);
        registerLimitConfig.setLimitCount(limitCount);
        System.out.println("RegisterLimitConfig:" + registerLimitConfig);

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();
        // 只对user注册接口进行控制
        if (!path.startsWith("/user/register")) {
            return chain.filter(exchange);
        }

        String clientIP = request.getRemoteAddress().getHostString();

        // 判断是否注册过于频繁
        Boolean isToolFrequent = registerChecker.checkFrequency(
                clientIP,
                registerLimitConfig.getLimitMinutes(),
                registerLimitConfig.getLimitCount());
        if (!isToolFrequent) {
            return chain.filter(exchange);
        }

        response.setStatusCode(HttpStatus.FORBIDDEN); // 状态码
        String respInfo = "您频繁进⾏注册，请求已被拒绝";
        DataBuffer wrap =
                response.bufferFactory().wrap(respInfo.getBytes());

        return response.writeWith(Mono.just(wrap));

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
